﻿using System;
using Microsoft.VisualStudio.TestTools.WebTesting;

namespace InfoPathExtractionRules
{
    public class ExtractEditingSessionId : ExtractionRule
    {
        /// When interacting with an InfoPath form in the browser, the server assigns the client
        /// an editing session id.
        /// This value is required for subsequent postbacks to the server
        /// The editing session id value is set in a javascript array
        /// We are trying to extract that value from the javascript array
        public override void Extract(object sender, ExtractionEventArgs e)
        {
            string var = IPExtractionUtil.getg_ObjCurrentFormData(e.Response.BodyString);
            if (string.IsNullOrEmpty(var))
            {
                e.Message = "Could not find g_ObjCurrentFormData";
                e.Success = false;
                return;
            }

            int index = (int)IPExtractionUtil.CurrentFormData.EditingSessionId;
            string editingSessionId = IPExtractionUtil.extractItemFromJavascriptArray(var, index);

            e.Success = true;
            if (string.IsNullOrEmpty(editingSessionId))
            {
                e.Message = "Could not find editingSessionId";
                e.Success = false;
                return;
            }

            editingSessionId = editingSessionId.Trim('"');


            e.WebTest.Context[this.ContextParameterName] = editingSessionId;
        }

        public override string RuleName
        {
            get { return "ExtractEditingSessionId"; }
        }
    }
}
